<?php
declare(strict_types=1);

namespace App\Service;

use App\Model\Entity\JnAdminUser;
use App\Model\Entity\Role;
use App\Model\Entity\UserRole;
use phpDocumentor\Reflection\Types\Mixed_;
use Swoft\Log\Helper\CLog;

/**
 * Class AdminUserService
 * @package App\Service
 */
class AdminUserService
{
    public function getInfo($userId) : array
    {
        $res =  JnAdminUser::find($userId)->toArray();
        return $res ? $res->toArray() : [];
    }

    public function getInfoByWhere(array $where) : array
    {
        $res  = JnAdminUser::whereProp($where)->first();
        return $res ? $res->toArray() :[];
    }

    /**
     * @param $userId
     * @param $data
     * @return mixed
     */
    public function edit($userId , $data)
    {
        return JnAdminUser::find($userId)->update($data);
    }

    public function addUserSimple($mobile , $suppliersUserId = 0) :int
    {
        $adminInfo= [];
        $adminInfo['userName']      = $mobile;
        $adminInfo['ecSalt']        = mt_rand(1000,9999);
        $adminInfo['password']      = $this->generatePassword($mobile , $adminInfo['ecSalt']);
        $adminInfo['email']         = '';
        $adminInfo['adminName']     = $mobile;
        $adminInfo['adminMobile']   = $mobile;
        $adminInfo['status']        = 0;
        $adminInfo['suppliersUserId'] = $suppliersUserId;
        $adminInfo['actionList']    = '';
        $adminInfo['navList']       = '';
        $adminInfo['agencyId']      = 0;

        return (int)JnAdminUser::insertGetId($adminInfo);
    }

    public function assignAuthority($adminUserId , $role_list)
    {
        $roles = Role::whereIn('role' ,$role_list)->get()->toArray();
        if (!$roles) return false;

        $roleIds = array_column($roles , 'roleId');

        //查询是否已经存在权限

        $roleIds_had = UserRole::where('user_id' , $adminUserId )->whereIn('role_id' , $roleIds)
                        ->get(['role_id'])->toArray();
        $roleIds_had  =  $roleIds_had  ? array_column($roleIds_had , 'roleId') : [];
        foreach($roleIds as $v)
        {
            if (!in_array($v , $roleIds_had)) {
                $data = [
                    'userId'    => $adminUserId ,
                    'roleId'    => $v ,
                ];
                UserRole::new($data)->save();
            }
        }

        return true;
    }

    private function generatePassword($password, $salt = '') :string
    {
        return md5(md5($password) . $salt);
    }

}